
package com.trial.area.goods.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.address.entity.DeliveryAddressVO;
import com.trial.area.address.service.DeliveryAddressService;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionUserInfo;
import com.trial.area.coupon.entity.CouponVO;
import com.trial.area.coupon.service.CouponService;
import com.trial.area.goods.entity.GoodsVO;
import com.trial.area.goods.param.GoodsParam;
import com.trial.area.goods.service.GoodsService;

/**
 * 商品Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class GoodsController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private GoodsService goodsService;
    
    @Autowired
    CouponService couponService;

    @Autowired
    DeliveryAddressService deliveryAddressService;

    private final static String LIST_PAGE = "/admin/goods/goods_list";

    private final static String VIEW_PAGE = "/admin/goods/goods_view";

    private final static String UPDATE_PAGE = "/admin/goods/goods_edit";
    
    private final static String H5_VIEW_PAGE = "/html5/goods/goods_view";
    
    private final static String H5_BUY_PAGE = "/html5/goods/goods_buy";
    
    private final static String H5_LIST_PAGE = "/html5/goods/goods_list";
    
    @RequestMapping(value = "/admin/goods/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        GoodsVO goodsVO = new GoodsVO();
        goodsVO.setGoodsStatus(1);
        goodsVO.setExDeliveryFee(new BigDecimal(30));
        goodsVO.setRemoteArea("新疆,西藏,青海省,宁夏,内蒙古,甘肃省");
        resultMap.put("goods", goodsVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/goods/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        GoodsVO goodsVO = goodsService.findById(id);

        resultMap.put("goods", goodsVO);

        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/goods/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(GoodsVO goodsVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer affectCount = 0;

            if (goodsVO != null && StringUtils.isNotBlank(goodsVO.getGoodsId())) {
                affectCount = goodsService.update(goodsVO);
            } else if (goodsVO != null) {
                goodsVO.setGoodsId(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
                goodsVO.setCreateUser(seUser.getUserId());
                goodsVO.setDataStatus(0);
                affectCount = goodsService.insert(goodsVO);
            }

            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改商品成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改商品失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改商品出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改商品出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/goods/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = goodsService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除商品成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除商品失败");
            }
        } catch (Exception e) {
            logger.error("删除商品出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除商品出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/goods/list")
    public ModelAndView queryAdminList(GoodsParam goodsParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<GoodsVO> dataList = goodsService.queryByPage(goodsParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", goodsParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/goods/view/{id}")
    public ModelAndView viewAdminInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        GoodsVO goodsVO = goodsService.findById(id);
        resultMap.put("goods", goodsVO);
        if (StringUtils.isNotBlank(goodsVO.getGoodsProperties())) {
            String[] properties = StringUtils.split(goodsVO.getGoodsProperties(), ":");

            String propertiesName = properties[0];
            
            resultMap.put("propertiesName", propertiesName);
            String[] propertiesList = StringUtils.split(properties[1], ",");
            
            resultMap.put("propertiesList", propertiesList);
        }
        return new ModelAndView(VIEW_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/goods/view/{id}")
    public ModelAndView viewInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        GoodsVO goodsVO = goodsService.findById(id);
        resultMap.put("goods", goodsVO);
        if (StringUtils.isNotBlank(goodsVO.getGoodsProperties())) {
            String[] properties = StringUtils.split(goodsVO.getGoodsProperties(), ":");

            String propertiesName = properties[0];
            
            resultMap.put("propertiesName", propertiesName);
            String[] propertiesList = StringUtils.split(properties[1], ",");
            
            resultMap.put("propertiesList", propertiesList);
        }
        return new ModelAndView(H5_VIEW_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/goods/list")
    public ModelAndView queryGoodsList(GoodsParam goodsParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<GoodsVO> dataList = goodsService.queryByPage(goodsParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", goodsParam);
        return new ModelAndView(H5_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/goods/buy")
    public ModelAndView buyPage(String goodsId, String selectProperty) {
        
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        
        if (seUser == null) {
            return new ModelAndView(H5_BUY_PAGE);
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        CouponVO couponVO = couponService.findByUserId(seUser.getUserId(), goodsId);
        
        resultMap.put("couponVO", couponVO);
        
        DeliveryAddressVO deliveryAddressVO = deliveryAddressService.findByUserId(seUser.getUserId());
        
        resultMap.put("deliveryAddressVO", deliveryAddressVO);
        
        GoodsVO goodsVO = goodsService.findById(goodsId);
        resultMap.put("goods", goodsVO);
        if (StringUtils.isNotBlank(goodsVO.getGoodsProperties())) {
            String[] properties = StringUtils.split(goodsVO.getGoodsProperties(), ":");
            
            String propertiesName = properties[0];
            
            resultMap.put("propertiesName", propertiesName);
            
            resultMap.put("selectProperty", selectProperty);
        }
        // 支付金额=商品原始运费+券码加收邮费金额
        if (couponVO != null) {
            BigDecimal tradeAmount = goodsVO.getDeliveryFee();
            if (couponVO.getExtraFee() != null) {
                tradeAmount = tradeAmount.add(couponVO.getExtraFee());
            }
            resultMap.put("tradeAmount", tradeAmount);
        }
        
        if (StringUtils.isNotBlank(goodsVO.getRemoteArea()) && deliveryAddressVO != null
            && StringUtils.contains(goodsVO.getRemoteArea(), deliveryAddressVO.getDeliveryProvince())) {
            resultMap.put("exDeliveryFee", goodsVO.getExDeliveryFee());
        }
        
        return new ModelAndView(H5_BUY_PAGE, resultMap);
    }
}
